<template>
  <s-clean-layout title="关系维护">
    <view class="page-container">
      <!-- 搜索区域 -->
      <view class="search-area">
        <view class="search-box">
          <uni-icons type="search" size="16" color="#999999"></uni-icons>
          <input 
            type="text"
            v-model="searchText"
            placeholder="搜索联系人"
            class="search-input"
          />
        </view>
        <view class="filter-btn" @tap="showFilter = true">
          <uni-icons type="filter" size="20" color="#666666"></uni-icons>
        </view>
      </view>

      <!-- 关系列表 -->
      <scroll-view class="relation-list" scroll-y>
        <!-- 新增关系行 -->
        <view v-for="(relation, index) in filteredNewRelations" :key="'new-' + index" class="relation-card new">
          <view class="relation-info">
            <view class="contact-avatar" @tap="selectContact('source', index, 'new')">
              <image v-if="relation.sourceContact?.avatar" :src="relation.sourceContact.avatar" class="avatar" />
              <view v-else class="avatar-placeholder">{{ getInitial(relation.sourceContact?.name) }}</view>
              <text class="name">{{ relation.sourceContact?.name || '选择联系人' }}</text>
            </view>
            
            <view class="relation-arrow" @tap="selectRelationType(index, 'new')">
              <uni-icons type="arrowthinright" size="20" color="#999999"></uni-icons>
              <text class="relation-text">{{ relation.type?.label }}</text>
            </view>
            
            <view class="contact-avatar" @tap="selectContact('target', index, 'new')">
              <image v-if="relation.targetContact?.avatar" :src="relation.targetContact.avatar" class="avatar" />
              <view v-else class="avatar-placeholder">{{ getInitial(relation.targetContact?.name) }}</view>
              <text class="name">{{ relation.targetContact?.name || '选择联系人' }}</text>
            </view>
          </view>
          
          <view class="operation">
            <uni-icons 
              type="trash" 
              size="20" 
              color="#FF3B30"
              @click="removeNewRelation(index)"
            />
          </view>
        </view>
        
        <!-- 现有关系列表 -->
        <view v-for="(relation, index) in filteredExistingRelations" :key="relation.id" class="relation-card">
          <view class="relation-info">
            <view class="contact-avatar" @tap="selectContact('source', index, 'existing')">
              <image v-if="relation.sourceContact?.avatar" :src="relation.sourceContact.avatar" class="avatar" />
              <view v-else class="avatar-placeholder">{{ getInitial(relation.sourceContact?.name) }}</view>
              <text class="name">{{ relation.sourceContact?.name }}</text>
            </view>
            
            <view class="relation-arrow" @tap="selectRelationType(index, 'existing')">
              <uni-icons type="arrowthinright" size="20" color="#999999"></uni-icons>
              <text class="relation-text">{{ relation.type?.label }}</text>
            </view>
            
            <view class="contact-avatar" @tap="selectContact('target', index, 'existing')">
              <image v-if="relation.targetContact?.avatar" :src="relation.targetContact.avatar" class="avatar" />
              <view v-else class="avatar-placeholder">{{ getInitial(relation.targetContact?.name) }}</view>
              <text class="name">{{ relation.targetContact?.name }}</text>
            </view>
          </view>
          
          <view class="operation">
            <uni-icons 
              type="trash" 
              size="20" 
              color="#FF3B30"
              @click="deleteRelation(relation)"
            />
          </view>
        </view>
      </scroll-view>

      <!-- 悬浮按钮 -->
      <view class="float-buttons">
        <view class="float-btn add" @tap="addNewRelation">
          <uni-icons type="plusempty" size="20" color="#FFFFFF"></uni-icons>
          <text>添加</text>
        </view>
        <view class="float-btn save" @tap="saveRelations" v-if="newRelations.length > 0">
          <uni-icons type="checkmarkempty" size="20" color="#FFFFFF"></uni-icons>
          <text>保存</text>
        </view>
      </view>
    </view>
    
    <!-- 联系人选择器 -->
    <s-contact-selector
      v-model:visible="showContactSelector"
      title="选择联系人"
      :multiple="false"
      v-model="tempSelectedContact"
      @confirm="handleContactConfirm"
    />
    
    <!-- 关系类型选择器 -->
    <s-type-selector
      v-model:visible="showRelationSelector"
      title="选择关系类型"
      :businType="'RELATIONSHIP'"
      @type-selected="handleRelationConfirm"
    />
  </s-clean-layout>
</template>

<script>
import { ref, computed } from 'vue';
import RelationApi from '@/sheep/api/contact/relation';

export default {
  components: {
    // TypeSelector
  },
  data() {
    return {
      searchText: '',
      showFilter: false,
      newRelations: [], // 新增的关系列表
      existingRelations: [], // 现有的关系列表
      showContactSelector: false,
      showRelationSelector: false,
      tempSelectedContact: [],
      tempSelectedRelation: null,
      currentEditIndex: -1,
      currentEditType: '', // 'source' 或 'target'
      editMode: 'new' // 'new' 表示编辑新增关系，'existing' 表示编辑现有关系
    }
  },
  computed: {
    // 过滤新增关系
    filteredNewRelations() {
      if (!this.searchText) return this.newRelations;
      
      return this.newRelations.filter(relation => {
        const sourceName = relation.sourceContact?.name || '';
        const targetName = relation.targetContact?.name || '';
        const relationType = relation.type?.label || '';
        
        return sourceName.includes(this.searchText) || 
               targetName.includes(this.searchText) || 
               relationType.includes(this.searchText);
      });
    },
    
    // 过滤现有关系
    filteredExistingRelations() {
      if (!this.searchText) return this.existingRelations;
      
      return this.existingRelations.filter(relation => {
        const sourceName = relation.sourceContact?.name || '';
        const targetName = relation.targetContact?.name || '';
        const relationType = relation.type?.label || '';
        
        return sourceName.includes(this.searchText) || 
               targetName.includes(this.searchText) || 
               relationType.includes(this.searchText);
      });
    }
  },
  onLoad() {
    this.loadRelations();
  },
  methods: {
    // 获取姓名首字母
    getInitial(name) {
      if (!name) return '?';
      return name.charAt(0).toUpperCase();
    },
    
    // 添加新关系行
    addNewRelation() {
      this.newRelations.push({
        sourceContact: null,
        targetContact: null,
        type: null
      });
    },
    
    // 移除新关系行
    removeNewRelation(index) {
      this.newRelations.splice(index, 1);
    },
    
    // 选择联系人
    selectContact(type, index, mode = 'new') {
      this.currentEditType = type;
      this.currentEditIndex = index;
      this.editMode = mode;
      this.tempSelectedContact = [];
      this.showContactSelector = true;
    },
    
    // 处理联系人选择
    handleContactConfirm(selected) {
      if (selected.length > 0 && this.currentEditIndex > -1) {
        const contact = selected[0];
        
        if (this.editMode === 'existing') {
          // 如果是编辑现有关系，先检查是否已经移动到新关系列表
          const existingRelation = this.existingRelations[this.currentEditIndex];
          if (existingRelation) {
            // 移动到新关系列表
            const modifiedRelation = { ...existingRelation, isModified: true };
            if (this.currentEditType === 'source') {
              modifiedRelation.sourceContact = contact;
            } else {
              modifiedRelation.targetContact = contact;
            }
            this.newRelations.push(modifiedRelation);
            this.existingRelations.splice(this.currentEditIndex, 1);
          }
        } else {
          // 处理新增关系
          const relations = this.newRelations;
          if (this.currentEditType === 'source') {
            relations[this.currentEditIndex].sourceContact = contact;
          } else {
            relations[this.currentEditIndex].targetContact = contact;
          }
        }
      }
      this.showContactSelector = false;
    },
    
    // 选择关系类型
    selectRelationType(index, mode = 'new') {
      this.currentEditIndex = index;
      this.editMode = mode;
      const relations = mode === 'new' ? this.newRelations : this.existingRelations;
      this.tempSelectedRelation = relations[index]?.type || null;
      this.showRelationSelector = true;
    },
    
    // 处理关系类型选择
    handleRelationConfirm(type) {
      if (type && this.currentEditIndex > -1) {
        if (this.editMode === 'existing') {
          // 如果是编辑现有关系，将其移动到新增关系列表中进行统一处理
          const existingRelation = this.existingRelations[this.currentEditIndex];
          if (existingRelation) {
            existingRelation.type = {
              id: type.id,
              value: type.id,
              label: type.name || type.label,
              icon: type.icon
            };
            // 将现有关系移到新关系列表中（用于保存时统一处理）
            this.newRelations.push({
              ...existingRelation,
              isModified: true // 标记为修改的现有关系
            });
            // 从现有关系列表中移除
            this.existingRelations.splice(this.currentEditIndex, 1);
          }
        } else {
          // 处理新增关系
          const relations = this.newRelations;
          if (relations[this.currentEditIndex]) {
            relations[this.currentEditIndex].type = {
              id: type.id,
              value: type.id,
              label: type.name || type.label,
              icon: type.icon
            };
          }
        }
        // 强制触发视图更新
        this.$forceUpdate();
      }
      this.showRelationSelector = false;
    },
    
    // 加载现有关系
    async loadRelations() {
      try {
        const res = await RelationApi.queryContactRelations();
        if (res.code === 0) {
          this.existingRelations = res.data.map(item => ({
            id: item.id,
            sourceContact: {
              id: item.sourceId,
              name: item.sourceContactName,
              avatar: item.sourceContactAvatarUrl
            },
            targetContact: {
              id: item.targetId,
              name: item.targetContactName,
              avatar: item.targetContactAvatarUrl
            },
            type: {
              value: item.type,
              label: item.typeName
            }
          }));
        }
      } catch (error) {
        uni.showToast({ title: '加载关系失败', icon: 'none' });
      }
    },
    
    // 保存关系
    async saveRelations() {
      if (!this.newRelations.length) return;
      try {
        const relationsToSave = this.newRelations
          .filter(relation => 
            relation.sourceContact && 
            relation.targetContact && 
            relation.type &&
            relation.sourceContact.id !== relation.targetContact.id
          )
          .map(relation => ({
            id: relation.isModified ? relation.id : null, // 修改的现有关系保留id，新增的关系id为null
            sourceId: relation.sourceContact.id,
            targetId: relation.targetContact.id,
            type: relation.type.value
          }));
        const res = await RelationApi.batchUpdateContactRelation({ relations: relationsToSave });
        if (res.code === 0) {
          uni.showToast({ title: '保存成功', icon: 'success' });
          this.loadRelations();
          this.newRelations = [];
        }
      } catch (error) {
        uni.showToast({ title: '保存失败', icon: 'none' });
      }
    },
    
    // 删除关系
    async deleteRelation(relation) {
      uni.showModal({
        title: '提示',
        content: '确定要删除这条关系吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const result = await RelationApi.deleteContactRelation({ id: relation.id });
              if (result.code === 0) {
                uni.showToast({ title: '删除成功', icon: 'success' });
                this.loadRelations();
              }
            } catch (error) {
              uni.showToast({ title: '删除失败', icon: 'none' });
            }
          }
        }
      });
    }
  }
}
</script>

<style lang="scss">
.page-container {
  min-height: 100vh;
  width: 100%;
  max-width: 100vw;
  display: flex;
  flex-direction: column;
  background-color: #F5F5F5;
  box-sizing: border-box;
  padding: 0 24rpx;
}

.search-area {
  display: flex;
  align-items: center;
  padding: 24rpx 0 12rpx 0;
  background-color: #FFFFFF;
  width: 100%;
  box-sizing: border-box;
}

.search-box {
  flex: 1;
  display: flex;
  align-items: center;
  background-color: #F5F5F5;
  border-radius: 32rpx;
  padding: 18rpx 28rpx;
  margin-right: 10rpx;
  box-sizing: border-box;
}

.search-input {
  flex: 1;
  margin-left: 10rpx;
  font-size: 18px;
  background: transparent;
  border: none;
  outline: none;
  color: #333;
  height: 48rpx;
  line-height: 48rpx;
}

.filter-btn {
  padding: 10rpx;
}

.relation-list {
  flex: 1;
  overflow: auto;
  padding: 0;
  width: 100%;
  box-sizing: border-box;
}

.relation-card {
  background-color: #FFFFFF;
  border-radius: 16rpx;
  padding: 16rpx 18rpx;
  margin-bottom: 18rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.03);
  border: 1rpx solid #f0f0f0;
  display: flex;
  align-items: center;
  width: 100%;
  box-sizing: border-box;
  overflow: hidden;
  &.new {
    border: 2rpx solid #8B5CF6;
    background: #faf5ff;
  }
}

.relation-info {
  display: flex;
  align-items: center;
  flex: 1 1 0%;
  min-width: 0;
  width: 100%;
  gap: 18rpx;
  overflow: hidden;
}

.contact-avatar {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 0;
  flex: 1 1 0;
  padding: 0 2rpx;
}

.avatar, .avatar-placeholder {
  width: 48rpx;
  height: 48rpx;
  border-radius: 50%;
  margin-bottom: 4rpx;
  background: #8B5CF6;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20rpx;
  object-fit: cover;
}

.avatar {
  object-fit: cover;
  background: #8B5CF6;
}

.name {
  font-size: 13px;
  color: #333333;
  width: 100%;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.relation-arrow {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 36rpx;
  flex: 1 1 0;
  justify-content: center;
}

.relation-text {
  font-size: 13px;
  color: #666666;
  margin-top: 2rpx;
}

.operation {
  display: flex;
  align-items: center;
  flex-shrink: 0;
  margin-left: 12rpx;
  height: 100%;
  background: transparent;
  padding: 0;
}

.operation uni-icons {
  background: #fff;
  border-radius: 50%;
  padding: 8rpx;
  box-sizing: border-box;
  transition: background 0.2s;
  font-size: 22rpx;
  color: #FF3B30;
  display: flex;
  align-items: center;
  justify-content: center;
}

.operation uni-icons:active {
  background: #f5f5f5;
}

.float-buttons {
  position: fixed;
  right: 24rpx;
  bottom: 48rpx;
  z-index: 10;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.float-btn {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  
  &.add {
    background: #8B5CF6;
  }
  
  &.save {
    background: #10B981;
  }
  
  text {
    font-size: 12px;
    color: #FFFFFF;
    margin-top: 4rpx;
  }
}
</style> 